# coding:utf-8
"""
description:scene 页面
"""
import os
import random

from pages.Devices.ConditionDevice_page import ConditionDevice_page
from appium.webdriver.common import mobileby

from common.Gesture_Mainpulation import gesture_mainpulation
from common.Get_Yaml import get_yaml
from common.Log import LOG
from config.GlobalParameter import TEST_Element_YAML

Scenes_Data = get_yaml(os.path.join(TEST_Element_YAML, 'Scenes.yaml'))


class ScenesList_page(ConditionDevice_page):
    by = mobileby.MobileBy()

    def func_SceneName(self):
        """
        验证SceneName方法
        :return:
        """
        self.click_Addscenes2_All()
        self.click_AddSceneAllLights()

    def func_AddTemplateScene(self, name, message):
        """
        添加light on或者light off模板
        :param name: 修改的name
        :param message:
        :return:
        """
        super().input_EditName(name)
        super().click_InputPopupSave()
        self.click_EditSceneSave()
        return self.find_toast(message)

    def func_AddCustomizeScene(self):
        # customize create home
        self.click_Addscenes2_All()
        self.click_AddAddSceneCustomize()
        self.click_SceneAddTask()

    def func_AddSceneTask(self, LoopN=1):
        """
        再次添加task避免进行编辑不够
        :param LoopN:
        :return:
        """
        for i in range(LoopN):
            self.click_SceneAddTask()
            self.click_TaskDevices()
            self.func_taskDevice()  # 随机点击选择task device

    def func_excuteScene(self, excuteScene, message):
        """
        根据Scene name点击执行scene
        :param excuteScene:
        :param message:
        :return:
        """
        for index, row in enumerate(self.getAdded_SceneName()):
            print("根据Scene name点击执行scene--%s" % row.text)
            if excuteScene in row.text:
                self.get_scenesList()[index].click()  # 点击scene列表项执行
            return self.find_toast(message)

    def func_Autoscene(self):
        """
        选择automation ，并选择rule方式
        :return:
        """
        self.click_switchEditSceneAutomation()
        self.click_EditSceneRule()

    def func_enterCondition(self, case=0):
        """
        点击进入condition device page
        :param case: 1，验证schedule time相同。0，选择condition
        :return:
        """
        self.click_switchEditSceneAutomation()  # 打开开关
        self.swipe_AddAndEditPage()  # 滑动页面显示最下面的condition +号按钮
        self.click_SceneAddCondition()
        if case == 1:
            super().func_ConditionScheduleNUll()  # schedule time 相同，save
        else:
            self.click_ConditionDevices()
            super().func_ConditionDevice()  # 随机点击condition device

    def func_enterTask(self):
        """
        点击进入task device page
        :return:
        """
        self.click_SceneAddTask()

    """点击左上角+号添加scene"""
    Addscenes1_loc = (by.XPATH, Scenes_Data.get_elementInfo(0))
    """点击底部add scenes按钮"""
    Addscenes2_loc = (by.CLASS_NAME, Scenes_Data.get_elementInfo(1))
    """scenes列表项集合"""
    scenesList_loc = (by.ID, Scenes_Data.get_elementInfo(2))

    """点击自定义模板项"""
    AddSceneCustomize_loc = (by.ID, Scenes_Data.get_elementInfo(3))
    """点击默认有on和off tasks的模板项"""
    AddSceneAllLights_loc = (by.ID, Scenes_Data.get_elementInfo(4))

    """滑动scene模板列表"""
    SceneswipeBar_loc = (by.ID, Scenes_Data.get_elementInfo(5))

    def click_Addscenes1(self):
        """点击左上角+号添加scene"""
        self.find_element(*self.Addscenes1_loc).click()

    def click_Addscenes2_All(self):
        """点击底部add scenes按钮"""
        if random.randint(1, 2) == 1:
            LOG.info("点击底部Add scene按钮...")
            self.find_element(*self.Addscenes2_loc).click()
        else:
            LOG.info("点击右上角'+'icon 添加按钮...")
            self.click_Addscenes1()

    def get_scenesList(self):
        """
        获取已添加的scene列表项
        :return: list
        """
        return self.find_elements(*self.scenesList_loc)

    def click_AddAddSceneCustomize(self):
        """点击自定义模板项"""
        self.find_element(*self.AddSceneCustomize_loc).click()

    def click_AddSceneAllLights(self):
        """上滑scene模板列表"""
        try:
            gesture_mainpulation().swipe_up(self.driver, self.find_elements(*self.SceneswipeBar_loc)[-1])
        except:
            LOG.error("滑动失败，检查被测设备的坐标是否能正常操作。。。")
        """点击默认有on和off tasks的模板项"""
        self.find_element(*self.AddSceneAllLights_loc).click()

    """点击修改scene name一行"""
    EditSceneName_loc = (by.ID, Scenes_Data.get_elementInfo(6))
    """点击add task一行，跳转可作为task的设备列表页"""
    SceneAddTask_loc = (by.ID, Scenes_Data.get_elementInfo(7))
    """点击编辑scene的task device页面delete按钮"""
    TaskActionDelete_loc = (by.ID, Scenes_Data.get_elementInfo(13))
    """点击编辑scene的condition device页面delete按钮"""
    ConditionActionDelete_loc = (by.ID, Scenes_Data.get_elementInfo(14))
    """点击编辑scene的Schedule和timer页面delete按钮"""
    ConditionScheduleDelete_loc = (by.ID, Scenes_Data.get_elementInfo(15))
    """获取add or edit scene页面已选择的device name"""
    SceneDeviceName_loc = (by.ID, Scenes_Data.get_elementInfo(16))

    def click_EditSceneName(self):
        """点击修改scene name一行"""
        self.find_element(*self.EditSceneName_loc).click()

    def click_SceneAddTask(self):
        """点击add task一行，跳转可作为task的设备列表页"""
        self.find_element(*self.SceneAddTask_loc).click()

    def click_TaskActionDelete(self):
        """点击编辑scene的task device页面delete按钮"""
        self.find_element(*self.TaskActionDelete_loc).click()

    def click_ConditionActionDelete(self):
        """点击编辑scene的condition device页面delete按钮"""
        self.find_element(*self.ConditionActionDelete_loc).click()

    def click_ConditionScheduleDelete(self):
        """点击编辑scene的Schedule和timer页面delete按钮"""
        self.find_element(*self.ConditionScheduleDelete_loc).click()

    def get_EditDevicesIcon(self):
        """获取scene编辑页面已存在的device"""
        return self.find_elements(*super().ConditionDevices_loc)

    def get_SceneDeviceName(self, indexs):
        """获取add or edit scene页面已选择的 task device name"""
        Devname = self.find_elements(*self.SceneDeviceName_loc)
        return Devname[indexs].text

    def swipeAndclick_EditDevicesDelete(self, indes=0):
        """从手机横x值滑动到编辑scene页面的task 或 condition device icon图标位置，点击最右侧删除"""
        try:
            Maxinumxy = gesture_mainpulation().get_sizes(self.driver)
            deviconXY = gesture_mainpulation().centreXAndY(self.get_EditDevicesIcon()[indes])  # 最左侧Device icon图标坐标获取
            self.driver.swipe(Maxinumxy[0] - 10, deviconXY[1], deviconXY[0], deviconXY[1],
                              200)  # 滑动back图标>>Device icon图标
            """根据滑动后，手机横轴x坐标为delete 按钮，则点击"""
            self.driver.tap([(Maxinumxy[0] - 30, deviconXY[1])])
        except:
            LOG.error("滑动失败，检查被测设备的坐标是否能正常操作。。。")

    def func_SceneEditName(self, scenename):
        """
        修改scene 默认name
        :param scenename:
        :return:
        """
        if self.assertVisible(*self.NameInputPopup_loc) == False:
            self.click_EditSceneName()
        # 填入正确的scene name
        self.input_EditName(scenename)
        self.click_EditSceneSave()

    def func_EditScene_ItemDelete(self, indexs=0):
        """
        edit scene，根据已添加的task item索引号左滑点击删除
        :param indexs:
        :return:
        """
        """删除第一个task device"""
        self.swipeAndclick_EditDevicesDelete(indexs)
        super().click_confirm()

    def func_EditScene_DelTaskOrReaddAction(self, indexs=0, indexs2=0, upAndDown="up", times=1):
        """
        根据已添加的task索引号，跳转页面，随机进行删除或重新选择action
        :param indexs:已添加的task或者condition索引号
        :param indexs2:
        :param upAndDown:
        :param times:
        :return:
        """
        self.get_EditDevicesIcon()[indexs].click()
        if random.randint(1, 2) == 1:
            super().func_taskDevice(indexs2, upAndDown, times)  # 重新随机选择device的action
        else:
            if super().assertVisible(*self.TaskActionDelete_loc):
                """判断跳入task页面，则点击delete按钮"""
                self.click_TaskActionDelete()
                super().click_confirm()
            else:
                """判断跳入没有delete按钮的IR control 页面，直接返回"""
                super().click_confirm()

    def func_EditScene_editRule(self, indexs=0, upAndDown="up", times=1):
        """
        编辑scene rule方式
        :return:
        """
        self.click_EditSceneRule()
        super().func_NumberPickerComfirm(indexs, upAndDown, times)

    def func_EditScene_DelConditionDev(self, indexs=-1):
        """
        随机删除condition ，区分schedule、timer和其他condition dev 页面的删除,
        或重新更改condition action
        :param indexs:
        :return:
        """
        self.swipe_AddAndEditPage()  # 滑动页面显示最下面的condition +号按钮
        self.get_EditDevicesIcon()[indexs].click()
        if self.assertVisible(*super().ScheduleRepeat_loc):
            LOG.info("删除condition schedule、timer...")
            self.click_ConditionScheduleDelete()
            super().click_confirm()

        else:
            if random.randint(1, 2) == 1:
                LOG.info("删除其他condition dev...")
                self.click_ConditionActionDelete()
                super().click_confirm()

            else:
                LOG.info("重新更改condition dev action...")
                super().func_ConditionDevice()

    def func_EditScene_Readdtask(self):
        """
        选择选择标识为added的设备应该要有提示
        :return:
        """
        self.func_enterTask()
        # if super().assertVisible(*self.AddedDevice_loc)==True:
        #
        super().click_AddedDevice()

    def func_EditScene_ReaddCondition(self):
        """
        重新进入condition列表页
        :return:
        """
        self.func_enterCondition()
        self.click_ConditionDevices()
        super().func_ConditionDevice()

    """Automated this scene开关"""
    switchEditSceneAutomation_loc = (by.ID, Scenes_Data.get_elementInfo(8))
    """点击Automated　this scene rule一行"""
    EditSceneRule_loc = (by.ID, Scenes_Data.get_elementInfo(9))
    """点击add condition一行，跳转可作为condition的设备列表页"""
    SceneAddCondition_loc = (by.ID, Scenes_Data.get_elementInfo(10))

    def click_switchEditSceneAutomation(self):
        """Automated this scene开关"""
        cbAuto = self.find_element(*self.switchEditSceneAutomation_loc)
        if cbAuto.get_attribute("checked") == 'false':  # 如果没有打开Automation switch则点击打开
            cbAuto.click()

    def click_EditSceneRule(self):
        """点击Automated　this scene rule一行"""
        self.find_element(*self.EditSceneRule_loc).click()

    def click_SceneAddCondition(self):
        """点击add condition一行，跳转可作为condition的设备列表页"""
        self.find_element(*self.SceneAddCondition_loc).click()

    """点击edit和add scene页面的右上角save按钮
    点击Emergency页面的右上角save按钮"""
    EditSceneSave_loc = (by.ID, Scenes_Data.get_elementInfo(11))

    def click_EditSceneSave(self):
        """点击edit和add scene页面的右上角save按钮。点击Emergency页面的右上角save按钮"""
        self.find_element(*self.EditSceneSave_loc).click()

    """获取已添加的scene列表名字，进行edit和删除"""
    cardSceneName_loc = (by.ID, Scenes_Data.get_elementInfo(12))

    def getAdded_SceneName(self):
        """
        根据获取已添加的scene列表名字进行edit和删除
        :return: 获取已添加的scene列表名字
        """
        return self.find_elements(*self.cardSceneName_loc)

    """滑动已添加的scene 列表"""
    swipeScene_loc = (by.ID, Scenes_Data.get_elementInfo(12))

    def swipeUP_addedScene(self):
        """向上滑动已添加的scene 列表"""
        cxy = gesture_mainpulation().centreXAndY(self.find_element(*self.swipeScene_loc))
        self.driver.swipe(cxy[0], cxy[1] + 300, cxy[0], cxy[1] - 300)

    def click_leftswipeEdit(self, CardSceneCard):
        """
        根据scene name左滑删除或者editscene。编辑的项一定要在前面
        :param CardSceneCard: scene name
        :return:
        """
        for index, row in enumerate(self.getAdded_SceneName()):
            if CardSceneCard in row.text:
                """先获取scene项坐标"""
                centre = gesture_mainpulation().centreXAndY(self.get_scenesList()[index])
                """再左滑scenes item后，出现Delete按钮并点击"""
                gesture_mainpulation().swipe_left(self.driver, row)
                """根据中间坐标推算edit坐标并点击"""
                self.driver.tap([(centre[0] + 150, centre[1])])
                break

    def func_deleteScene(self, message):
        """
        删除scene ，添加前删除全部
        :param message:
        :return:
        """
        if self.assertVisible(*self.scenesList_loc):
            """先获取scene项坐标"""
            centre = gesture_mainpulation().centreXAndY(self.get_scenesList()[0])  # 获取一次，只需要delete按钮坐标
            for i in range(len(self.get_scenesList())):
                """左滑scenes item后，出现Delete按钮并点击"""
                gesture_mainpulation().swipe_left(self.driver, self.get_scenesList()[0])
                """根据中间坐标推算Delete坐标并点击"""
                self.driver.tap([(centre[2] - 50, centre[1])])
                self.click_confirm()
                self.find_toast(message)
            return self.assertVisible(*self.Addscenes2_loc)  # 如果没有added scene，则断言底部Add scene按钮存在
        else:
            LOG.info("没找到已添加的scene列表项进行删除操作，下次执行在测试删除功能...")
            return True

    """滑动添加或者编辑scene的页面"""
    AddAndEditPage_loc = (by.ID, Scenes_Data.get_elementInfo(18))

    def swipe_AddAndEditPage(self):
        """滑动添加或者编辑scene的页面"""
        gesture_mainpulation().swipe_up(self.driver, self.find_element(*self.AddAndEditPage_loc))
